<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/11
 * Time: 15:01
 */

namespace app\base\service;
use app\base\logic\Coordinate;
use think\Config;
/**
 * Class Beidou
 * 北斗服务
 * @package app\base\service
 */
class Beidou
{
    /**
     * 获取北斗轨迹
     * @param string $license_plate 车牌
     * @param int $start_time 开始时间戳
     * @param int $end_time 结束时间戳
     * @return array 定位数组
     */
    public function getTrack($license_plate,$start_time, $end_time,$gcj=0){
        $len  = ceil(($end_time-$start_time) / 3600);
        $len  = $len ? $len : 1;
        $dir  = Config::get('base.bd_save_dir');
        $data       = [];
        $coordinate = [];
        // 替换车牌特殊字
        $license_plate = str_replace("黄","",$license_plate);
        $license_plate = str_replace("蓝","",$license_plate);
        $license_plate = str_replace("白","",$license_plate);
        $license_plate = str_replace("绿","",$license_plate);
        $license_plate = str_replace("黑","",$license_plate);
        // 循环读取轨迹
        for ($i=0; $i<=$len; $i++){
            $fileName    = $dir . md5($license_plate) . '/' . date('YmdH', $start_time + $i * 3600) . '.txt';
            if(file_exists($fileName)){
                $file    = file_get_contents($fileName);
                $records = explode("\r\n", trim($file));
                foreach ($records as $record) {
                    $row = explode("|", $record);
                    if(strtotime($row[11]) >= $start_time && strtotime($row[11]) <= $end_time){
                        $gcj ==1 && $coordinate = Coordinate::wgsTOgcj($row[4], $row[5]);
                        $rows['carId']      = $row[0];
                        $rows['carNo']      = $row[1];
                        $rows['gpsNo']      = $row[2];
                        $rows['simNo']      = $row[3];
                        $rows['longitude']  = $coordinate[0] ?: $row[4];
                        $rows['latitude']   = $coordinate[1] ?: $row[5];
                        $rows['speed']      = $row[6];
                        $rows['bearing']    = $row[7];
                        $rows['accuray']    = $row[8];
                        $rows['state']      = $row[9];
                        $rows['alarm']      = $row[10];
                        $rows['time']       = strtotime($row[11]);
                        $rows['mile']       = $row[12];
                        array_push($data,$rows);
                    }
                }
            }
        }
        return $data;
    }
}